<?php 
	
	function encode($str){

		$words = explode(" ", $str);
		$result = '';
		foreach ($words as $word) {

			$opt = array();
			$opt = explode("?", $word);
			
			if(mb_strtoupper($opt[2]) == 'B'){
			
				$tmp_result = base64_decode($opt[3]);
			
			} elseif(mb_strtoupper($opt[2]) == 'Q') {
			
				$tmp_result = quoted_printable_decode($opt[3]);
			
			}

			if(mb_strtoupper($opt[1]) != 'UTF-8') {
				$tmp_result = iconv($opt[1], 'UTF-8', $tmp_result);
			}
			
			if(!$result) { 
				$result .= ' ';
			}

			$result .= $tmp_result;
			
		}

		return $result;
		
	}

	$mbox = imap_open("{imap.yandex.ru:993/ssl}INBOX", "bomberweb", "ggOnZo13q") or die("can't connect: " . imap_last_error());
	$MC = imap_check($mbox);
	$mails = array();

	// Fetch an overview for all messages in INBOX
	$result = imap_fetch_overview($mbox,"1:{$MC->Nmsgs}",0);
	foreach ($result as $overview) {

		$mails[$overview->uid]['uid'] = $overview->uid;
		$mails[$overview->uid]['date'] = date('d.m.y_H:i', strtotime($overview->date));
		$mails[$overview->uid]['from'] = encode($overview->from);
		$mails[$overview->uid]['to'] = encode($overview->to);
		$mails[$overview->uid]['subject'] = encode($overview->subject);
		$mails[$overview->uid]['msgno'] = $overview->msgno;

	}
	imap_close($mbox);

?><!DOCTYPE html>
<html lang="ru">
<head>
	<meta charset="UTF-8">
	<title>Mail client</title>
	<style>
		table tr td {
			border-bottom: black solid 1px;
			padding: 5px;
		}

		table tr:nth-child(2n+2) td {
			background: lightgray;
		}

	</style>
</head>
<body>
	<div>
		<table width="100%" border="0" cellspacing="0" cellpadding="0">
			<tr>
				<th>#</th>
				<th>Дата</th>
				<th>От кого</th>
				<!-- <th>Кому</th> -->
				<th>Тема сообщения</th>
			</tr>
		<?php

			arsort($mails);

			foreach ($mails as $k) {
				if($k['date'] && $k['from'] && $k['subject']) {
					print("<tr>");
					print("<td>" . $k['uid'] . "</td>");
					print("<td>" . $k['date'] . "</td>");
					print("<td>" . $k['from'] . "</td>");
					//print("<td>" . $k['to'] . "</td>");
					print("<td><a href='/mail.php?mail=" . $k['msgno'] . "'>" . $k['subject'] . "</a></td>");
					print("</tr>");
				}
			}
		?>
		</table>
	</div>
</body>
</html>